package model

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
	"log"
	"os"
)

// xorm: http://xorm.io/docs
var x *xorm.Engine

func InitDB() {
	dsn := os.Getenv("DB_DSN")
	driver := os.Getenv("DB_DRIVER")

	var err error
	x, err = xorm.NewEngine(driver, dsn)
	if err != nil {
		log.Fatalf("连接数据库失败：%v", err)
	}
	x.SetMapper(core.GonicMapper{})
	x.ShowSQL(true)

	err = x.Sync2(
		new(Address),
		new(Customer),
		new(Express),
		new(Order),
		new(Phone),
	)
	if err != nil {
		log.Fatalf("数据库同步失败：%v", err)
	}
}

func GetDB() *xorm.Engine {
	return x
}
